<template>
  <div>
    <div class="box">
      <!-- 是否绑定图表 -->
      <div class="flex_y_center">
        <div class="inp_title">是否绑定图表：</div>
        <el-radio-group v-model="punchForm.is_chart" @change="selRadio">
          <el-radio label="Y">是</el-radio>
          <el-radio label="N">否</el-radio>
        </el-radio-group>
        <el-tooltip
          content="选择后，会生成默认且不可修改的按钮名称，和打卡项，并在客户端使用该打卡功能进行打卡后，会根据打卡数据生成图表"
          effect="dark"
          placement="right"
          style="margin-left: 10px"
        >
          <el-icon class="el-icon-question" />
        </el-tooltip>
      </div>
      <!-- 打卡名称 -->
      <div class="flex_y_center">
        <div class="inp_title">
          <span>*</span>
          打卡名称：
        </div>
        <el-input
          v-model="punchForm.menu_name"
          :disabled="punchForm.is_chart == 'Y'"
          placeholder="请输入打卡名称"
          style="width: 30%"
        />
      </div>
      <!-- 背景色 -->
      <div class="flex_y_center">
        <div class="inp_title">
          <span>*</span>
          按钮背景色：
        </div>
        <el-color-picker v-model="punchForm.background" />
      </div>
      <!-- 上传图片 -->
      <div class="flex_y_center">
        <div class="inp_title">
          <span>*</span>
          上传图标：
        </div>
        <el-upload
          ref="upload"
          action=""
          :auto-upload="false"
          :on-change="selImg"
          :show-file-list="false"
        >
          <el-button slot="trigger" type="primary">选择图片</el-button>
        </el-upload>
      </div>
      <!-- 默认图片 -->
      <div class="flex_y_center">
        <div class="inp_title"></div>
        <img
          v-show="!punchForm.ico_image"
          :src="defaultSrc"
          style="width: 100px; height: 100px"
        />
        <el-image
          v-show="punchForm.ico_image"
          :src="punchForm.ico_image"
          style="width: 100px; height: 100px"
        />
      </div>

      <!-- 打卡项 -->
      <el-button type="primary" @click="push">添加打卡项</el-button>
      <el-table :data="extend_fields" style="margin-top: 10px">
        <el-table-column label="名称">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.name"
              :disabled="punchForm.is_chart == 'Y' && scope.$index < 3"
              placeholder="请输入名称"
            />
          </template>
        </el-table-column>
        <el-table-column label="类型">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.type"
              :disabled="punchForm.is_chart == 'Y' && scope.$index < 3"
              placeholder="请选择类型"
              @change="selType(scope.row)"
            >
              <el-option
                v-for="(item, index) of type"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="默认值">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.default"
              :disabled="
                (scope.row.type != 'input_str_w' &&
                  scope.row.type != 'input_num_w' &&
                  scope.row.type != 'input_str_r' &&
                  scope.row.type != 'input_num_r') ||
                (punchForm.is_chart == 'Y' && scope.$index < 3)
              "
              :placeholder="
                '请输入默认值' +
                (scope.row.type == 'input_str_r' ||
                scope.row.type == 'input_num_r'
                  ? '(必填)'
                  : '')
              "
            />
          </template>
        </el-table-column>
        <el-table-column label="内容">
          <template slot-scope="scope">
            <el-input
              v-if="
                scope.row.type != 'input_select' &&
                scope.row.type != 'input_checkbox' &&
                scope.row.type != 'input_radio'
              "
              disabled
              placeholder="请输入内容"
            />
            <!-- 下拉框选项 -->
            <div
              v-else-if="
                scope.row.type == 'input_select' ||
                scope.row.type == 'input_checkbox' ||
                scope.row.type == 'input_radio'
              "
            >
              <div
                v-for="(item, index) in scope.row.option"
                :key="index"
                class="flex_y_center"
              >
                <el-input
                  v-model="scope.row.option[index]"
                  style="margin: 0 5px 5px 0"
                />
                <el-button
                  type="text"
                  @click="scope.row.option.splice(index, 1)"
                >
                  移除
                </el-button>
              </div>
              <el-button @click="scope.row.option.push('')">添加</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.unit"
              :disabled="
                scope.row.type == 'input_date' ||
                scope.row.type == 'input_time' ||
                (punchForm.is_chart == 'Y' && scope.$index < 3)
              "
              placeholder="请输入单位"
            />
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template slot-scope="scope">
            <el-button
              :disabled="punchForm.is_chart == 'Y' && scope.$index < 3"
              type="danger"
              @click="extend_fields.splice(scope.$index, 1)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex_between">
      <div></div>
      <el-button type="primary" @click="addGrowth">保存</el-button>
    </div>
  </div>
</template>

<script>
  import { addGrowthMenu } from '@/api/punch'
  import { getImg } from '@/api/public'

  export default {
    props: {
      oPunchDetils: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      return {
        menuItem: [],
        selBool: false,
        type: [
          {
            name: '文字输入',
            id: 'input_str_w',
          },
          {
            name: '文字输入(只读)',
            id: 'input_str_r',
          },
          {
            name: '下拉菜单',
            id: 'input_select',
          },
          {
            name: '数字输入',
            id: 'input_num_w',
          },
          {
            name: '数字输入(只读)',
            id: 'input_num_r',
          },
          {
            name: '单选',
            id: 'input_radio',
          },
          {
            name: '复选',
            id: 'input_checkbox',
          },
          {
            name: '日期选择',
            id: 'input_date',
          },
          {
            name: '时间选择',
            id: 'input_time',
          },
        ],

        // 默认图标
        defaultSrc: 'https://s3.bmp.ovh/imgs/2022/05/13/b0d463610ba2fcb5.png',
        extend_fields: [
          { name: '', type: 'input_date', default: '', unit: '' },
        ],
        punchForm: {
          id: '',
          is_chart: 'N', // 是否绑定图表
          menu_name: '', // 按钮名称
          extend_fields: '', // 打卡字段，是一个JSON数组
          ico_image: '', // 图标
          background: '', // 背景色，16进制颜色码
        },
        hint: {
          menu_name: '按钮名称',
          background: '按钮背景色',
        },
      }
    },
    created() {
      this.assignForm()
    },
    methods: {
      // 将需要的数据赋值到相同属性值上
      assignForm() {
        if (JSON.stringify(this.oPunchDetils) != '{}') {
          for (let item in this.punchForm) {
            if (item == 'extend_fields')
              this.extend_fields = JSON.parse(this.oPunchDetils[item])
            else this.punchForm[item] = this.oPunchDetils[item]
          }
        } else {
          for (let item in this.punchForm) {
            if (item != 'is_chart') this.punchForm[item] = ''
          }
          this.extend_fields = [
            { name: '', type: 'input_date', default: '', unit: '' },
          ]
        }
      },

      // 选择是否关联图表
      selRadio(e) {
        if (e == 'Y') {
          const extend = [
            { name: '日期', type: 'input_date', default: '', unit: '' },
            { name: '身高', type: 'input_str_w', default: '0.0', unit: 'cm' },
            { name: '体重', type: 'input_str_w', default: '0.0', unit: 'kg' },
          ]
          // this.extend_fields = [...this.extend_fields, ...extend]
          this.extend_fields = [...extend, ...this.extend_fields]
          this.punchForm.menu_name = '身高打卡'
        } else {
          this.extend_fields.splice(0, 3)
          this.punchForm.menu_name = ''
        }
      },
      // 选择图片并上传到服务器
      selImg(file) {
        // 判断选择上传的图片文件类型，只允许上传jpg，png格式
        if (file.raw.type == 'image/jpg' || file.raw.type == 'image/png') {
          if (file.size / 1024 / 1024 < 0.25) {
            let formData = new FormData()
            formData.append('file', file.raw)

            // 调用图片上传接口
            getImg(formData).then((res) => {
              this.$message.success('图片上传成功')
              this.punchForm.ico_image = res.data
            })
          } else {
            this.$message.error('只能上传 25 * 25 大小的图标，请重新选择')
          }
        } else {
          this.$message.error('只支持jpg和png的图片文件上传')
        }
      },
      // 给menuItem变量添加数据
      push() {
        this.extend_fields.push({
          name: '',
          type: '',
          default: '',
          unit: '',
        })
      },
      // 选择拓展字段类型
      selType(row) {
        if (
          row.type != 'input_select' &&
          row.type != 'input_checkbox' &&
          row.type != 'input_radio'
        ) {
          if (row.option) this.$delete(row, 'option')
        } else {
          this.$set(row, 'option', [''])
        }
      },
      // 删除指定位置的项
      delmenuItem(index) {
        if (this.extend_fields.length == 1)
          this.$message.error('必须保留最后一项')
        else this.extend_fields.splice(index, 1)
      },
      // 添加打卡
      addGrowth() {
        // 检索基础输入项是否存在漏写
        for (let item in this.hint) {
          if (!this.punchForm[item]) {
            this.$message.error(this.hint[item] + '未填写')
            return
          }
        }
        // 检索拓展字段
        for (let i = 0; i < this.extend_fields.length; i++) {
          if (this.extend_fields[i].name == '') {
            this.$message.error('第' + (i + 1) + '个打卡项名称未填写')
            return
          }
          const type = this.extend_fields[i].type
          if (type == 'input_str_r' || type == 'input_num_r') {
            if (this.extend_fields[i].default == '') {
              this.$message.error('第' + (i + 1) + '个打卡项默认值必须填写')
              return
            }
          }
          if (
            type == 'input_select' ||
            type == 'input_radio' ||
            type == 'input_checkbox'
          ) {
            for (let item of this.extend_fields[i].option) {
              if (item == '') {
                this.$message.error('内容部分请输入完整')
                return
              }
            }
          }
        }

        if (typeof this.extend_fields != 'string') {
          this.punchForm.extend_fields = JSON.stringify(this.extend_fields)
        }
        // 判断是否选择了图片，没有选择的话那么将默认图标上传到服务器
        if (this.punchForm.ico_image == '')
          this.punchForm.ico_image = this.defaultSrc
        const data = this.punchForm
        addGrowthMenu(data).then(() => {
          this.$emit('send')
        })
      },
    },
  }
</script>

<style scoped>
  span {
    color: red;
  }
  .inp_title {
    width: 110px;
    text-align: right;
  }

  .box > div {
    margin-bottom: 10px;
  }
</style>
